import { useMemberStore } from '@/stores'

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

//添加拦截器
const httpInterceptor = {
  //拦截之前触发 UniNamespace.RequestOptions 和 UniApp.RequestOptions 本质上是 同一个类型，只是在不同版本的 UniApp 或不同环境下可能使用了不同的命名空间导出
  invoke(options: UniNamespace.RequestOptions) {
    //拼接路径
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }

    //设置header
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    //设置token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
    options.timeout = 10000
  },
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: string
  msg: string
  data: T
}

export const http = <T>(options: UniNamespace.RequestOptions) => {
  //返回promise对象
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      //请求成功
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          //提取核心数据
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          //401错误，清理用户信息
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({ url: '//pages/login/login' }).then((r) => {
            reject(r)
          })
        } else {
          uni
            .showToast({
              icon: 'none',
              title: (res.data as Data<T>).msg || '请求失败',
            })
            .then((r) => reject(r))
        }
      },

      fail(err) {
        uni
          .showToast({
            icon: 'none',
            title: '网络错误换个网络试试',
          })
          .then((r) => reject(r))
      },
    })
  })
}
